# -*- coding: utf-8 -*-
from PySide2 import QtWidgets
import maya.cmds as mc
import os,  re
import DH_PySideUidata

#filepath = str(os.path.split(os.path.realpath(__file__))[0])
form_class, base_class = DH_PySideUidata.loadUiType('Y:/Reference/TD/maya2017/zszr_tools/dango/ZSZR_sceneCleaner.ui')


class DH_ZSZR_sceneCleaner(base_class, form_class):

    def __init__(self):
        self.window_name = 'DH_ZSZR_sceneCleaner'
        if mc.window(self.window_name, exists=True):
            mc.deleteUI(self.window_name)
        super(DH_ZSZR_sceneCleaner, self).__init__(parent=DH_PySideUidata.getMayaWindow())
        self.setupUi(self)
        desktop = QtWidgets.QApplication.desktop().availableGeometry()
        size = self.geometry()
        self.move((desktop.width()-size.width())/2, (desktop.height()-size.height())/2)
        
        self.cam_name_checker.clicked.connect(self.check_camname)
        self.fps_checker.clicked.connect(self.fps_check)
        self.referencEditor_checker.clicked.connect(self.check_namespace)
        self.high_model_cheker.clicked.connect(self.check_H_model)
        self.displayLayer_checker.clicked.connect(self.checkDisplayLayer)
        self.filename_checker.clicked.connect(self.check_filename_name)
        self.anim_start_checker.clicked.connect(self.check_start_frame)
        self.AD_checker.clicked.connect(self.AD_scene_check)
        self.apply_all.clicked.connect(self.applyAll)
   
    def resultOutput(self,content):# output the result of cleaning
        current_content = self.result_output.toPlainText()
        self.result_output.setText(current_content+content)
        self.result_output.setFontPointSize(12)
        
    def setColorGreen(self,whitch_button):# set the right option button color to green
        whitch_button.setStyleSheet("background-color: rgb(56, 113, 0);")
        
    def erroroutput(self,errorContent):# show the dialogue of error
        mc.confirmDialog(title=u'提示', message=errorContent, button=['ok'])
        
   
    def check_camname(self):# check cameraname
        file_name = mc.file(q=True, sn=True).encode('utf-8').split("/")[-1]
        if not file_name:
            self.resultOutput(u"1.未发现相机，请检查！\n")
        camName = "CAM_" +  file_name.split("_")[0] +"_"+ file_name.split("_")[1]
        #print camName
        if mc.objExists(camName):
            #mc.select("*"+camName+"*",r=1)
            selA = mc.ls("*"+camName+"*")
            axis_sum = self.check_axis(selA[0])
            if len(selA) == 2:
                #print selA
                if not axis_sum:
                    self.setColorGreen(self.cam_name_checker)
                    self.resultOutput(u"1.相机名为%s，符合规范.\n"%selA[0])
                    return True
                else:
                    self.resultOutput(u"1.相机旋转轴心被动过！请联系TD...\n")
                    return False
            else:
                #print selA
                #pass
                #self.erroroutput(u"存在多个相机！\n%s\n请检查."%selA) 
                self.resultOutput(u"1.可能存在多个相机！\n%s\n"%selA)
                return 
        else:
            #self.erroroutput(u"相机不存在！请检查.") 
            self.resultOutput(u"1.检查相机名发生错误！相机可能不存在或者命名不对.正确命名为%s\n"%camName)
            return 
            
    def check_axis(self,cam_name):
        attr_grp = ["rotateAxisX","rotateAxisY","rotateAxisZ","scalePivotX","scalePivotY","scalePivotZ"]
        axis_sum = 0
        for each_attr in attr_grp:
            axis_sum += mc.getAttr(cam_name+"."+each_attr)
        return axis_sum

    def fps_check(self):# check whether the fps is right or not 
        fpsString = mc.currentUnit(query=True,t=True)
        if fpsString == 'film':
            self.setColorGreen(self.fps_checker)
            self.resultOutput(u"2.fps为24，符合规范.\n")
            return True
        else:
            self.resultOutput(u"2.检查fps发生错误！\n")
            #self.erroroutput(u"fps不正确！请检查.")
            return 
            
            
    def check_namespace(self):
        invalid_no_namespace = []
        invalid_more_namespace = []
        invalid_namspace = []
        for ref in mc.ls(references=True):            
            try:
                filename = mc.referenceQuery(ref, filename=1)
                ns = mc.referenceQuery(ref, ns=1, shn=1)
                code = os.path.basename(filename).split("_")[0]
                
                nodes = mc.referenceQuery(ref,n=1)
                nodes = list(set([k.rpartition(":")[0] for k in nodes]))    
                if [k for k in nodes if ":" in k]:
                    invalid_more_namespace.extend(nodes)
                    
                if not ns:
                    invalid_no_namespace.append(filename)
                if ":" in ns:
                    invalid_more_namespace.append(ns)    
                if "_" in ns:
                    invalid_namspace.append(ns)
                    
                if not re.search(code, ns):
                    invalid_namspace.append(ns)                    
            except:
                continue
        
        if invalid_no_namespace:
            self.resultOutput(u"3.请打开referenceEditor，reference 不带 namespace {0}\n".format(invalid_no_namespace))
            return
        if invalid_more_namespace:
            self.resultOutput(u"3.请打开referenceEditor，reference 多层 namespace {0}\n".format(invalid_more_namespace))
            return            
        if invalid_namspace:
            self.resultOutput(u"3.请打开referenceEditor，reference namespace {0} 有问题,请检查\n".format(invalid_namspace))
            return
        if not (invalid_no_namespace and invalid_more_namespace and invalid_namspace):
            checkPath = self.check_reference_path()
            if checkPath:
                self.resultOutput(u"3.reference检查完毕，符合规范.\n")
                self.setColorGreen(self.referencEditor_checker)
        return True
    
    def check_reference_path(self):
        invalid = []        
        for ref in mc.ls(references=True):   
            try:
                filename = mc.referenceQuery(ref, filename=1)
                search = re.search("T:/projects/zszr/assets", filename)
                if not search:
                    invalid.append(filename)
            except:
                continue
        if invalid:
            self.resultOutput(u"3.引用目录错误，只允许在 T:/projects/zszr/assets, 请检查 {0}\n".format(invalid))
            return
        return True
    
    def check_H_model(self):#autoSwitch proxy to high
        all_sw_attr = mc.ls("*"+":Main.Model_Switch")
        errorList = []
        for eachAttr in all_sw_attr:
            if mc.getAttr(eachAttr) == 0:
                errorList.append(eachAttr.split(":")[0].encode('utf-8'))
        if len(errorList) == 0:
            self.setColorGreen(self.high_model_cheker)
            self.resultOutput(u"4.所有角色都已切换至高模.\n")
        else:
            #self.erroroutput(u"场景中存在角色未切换至高模，请查看右侧输出框!")
            self.resultOutput(u"4.以下角色未切换至高模，已自动切换！\n%s\n"%errorList)
            for eachUnswitched in errorList:
                mc.setAttr(eachUnswitched + ":Main.Model_Switch", 1)
            self.setColorGreen(self.high_model_cheker)
        return True

    def checkDisplayLayer(self):
        error_layers = []
        allow_layer = ["no_render", "templates"]
        error_layers.extend([k for k in [k for k in mc.ls(type="displayLayer") if k!="defaultLayer"] if k not in allow_layer])
        error_layers = [k.encode('utf-8') for k in error_layers if not mc.referenceQuery(k,inr=1)]
        if error_layers:
            mc.delete(error_layers)
            self.resultOutput(u"5.发现有自建层，已删除 {0}\n".format(error_layers))
            self.setColorGreen(self.displayLayer_checker)
            return True
        else:
            self.resultOutput(u"5.未发现自建显示层\n")
            self.setColorGreen(self.displayLayer_checker)
        return True
    
    def check_filename_name(self):
        filename = mc.file(q=1,sn=1).split("/")[-1]
        a = re.match(r'E\d{2}SH\d{3}_SC\d{3}_(layout|blocking|anim)_v\d{3}.ma',filename)
        if not a:
            self.resultOutput(u"6.文件命名不符合规范!请修改(必须是ma格式).\n")
            return
        else:
            self.resultOutput(u"6.文件名符合规范%s\n"%filename)
            self.setColorGreen(self.filename_checker) 
            return True
              
    def check_start_frame(self):
        start_frame = mc.playbackOptions(minTime=True, query=True)
        min_frame = mc.playbackOptions(ast=True, query=True)
        end_frame = mc.playbackOptions(maxTime=True, query=True)
        max_frame = mc.playbackOptions(aet=True, query=True)
        if not (start_frame == min_frame == 100 and end_frame == max_frame):
            mc.playbackOptions(minTime=100)
            mc.playbackOptions(ast=100)
            mc.playbackOptions(maxTime = max_frame)
            self.resultOutput(u"7.发现时间滑块未拉满或动画未从100f开始！已修正.\n")
            self.setColorGreen(self.anim_start_checker) 
        else:
            self.resultOutput(u"7.时间滑块正常，符合规范.\n")
            self.setColorGreen(self.anim_start_checker)
        return True
    
    
    def AD_scene_check(self):
        all_ad = mc.ls(r"*E*SH*_SC*_AD_AR*")
        extra_ad = []
        if len(all_ad) > 1 or len(all_ad) == 0:
            for eachad in  all_ad:
                if not mc.listRelatives(eachad,c=1):
                    extra_ad.append(eachad)
                    mc.delete(eachad)
            if extra_ad:
                self.resultOutput(u"8.已删除多余的场景AD文件%s\n"%extra_ad)
            leftAD = mc.ls(r"*E*SH*_SC*_AD_AR*")
            if not len(leftAD) == 1:
                self.resultOutput(u"8.不存在场景AD文件或者多余的场景文件未处理！\n")
                return
            self.setColorGreen(self.AD_checker)
            return True
        else:
            self.resultOutput(u"8.场景中只存在一个AD文件%s，符合规范\n"%all_ad[0]) 
            self.setColorGreen(self.AD_checker)
            return True
        
    
    def applyAll(self):
        checkNumber = 0
        if not self.check_camname():
            checkNumber+=1
        if not  self.fps_check():
            checkNumber+=1
        if not  self.check_namespace():
            checkNumber+=1
        if not  self.check_H_model():
            checkNumber+=1
        if not  self.checkDisplayLayer():
            checkNumber+=1
        if not  self.check_filename_name():
            checkNumber+=1
        if not  self.check_start_frame():
            checkNumber+=1
        if not  self.AD_scene_check():
            checkNumber+=1
        #print checkNumber
        if checkNumber == 0:
            mc.file(save =1)
            self.resultOutput(u"\n检查完成，均已符合规范，已自动保存文件.\n")

  
DH_ZSZR_sceneCleaner().show()      

    







